package com.toocms.jinjuhang.dialog.share

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.MediaScannerConnection
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.ToastUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.databinding.DialogCommodityShareBinding
import java.io.File

class CommodityShareDialog : DialogFragment() {
    var binding: DialogCommodityShareBinding? = null
    var viewModel: CommodityShareModel? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.dialog_commodity_share,
            container,
            false
        )
        viewModel = CommodityShareModel(this)
        binding!!.setVariable(BR.commodityShareModel, viewModel)
        return binding!!.root.apply {
            setOnLongClickListener {
                val qrBitmap = ImageUtils.view2Bitmap(it)
                var saveImagePath =
                    "${requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path}${File.pathSeparator}CommodityShare-${System.currentTimeMillis()}.png"
                ImageUtils.save(qrBitmap, saveImagePath, Bitmap.CompressFormat.PNG, 100)
                MediaStore.Images.Media.insertImage(
                    requireContext().contentResolver,
                    saveImagePath,
                    File(saveImagePath).name,
                    null
                )
                MediaScannerConnection.scanFile(
                    requireContext(),
                    arrayOf(saveImagePath),
                    null,
                    null
                )
                ToastUtils.showShort(R.string.str_save_succeed)
                true
            }
        }
    }

    override fun onStart() {
        super.onStart()
        config()
    }

    private fun displayMetrics() = resources.displayMetrics

    private fun config() {
        dialog?.run {
            setCancelable(true)
            setCanceledOnTouchOutside(true)
            window
        }?.apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setGravity(Gravity.CENTER)
            setLayout(
                (displayMetrics().widthPixels.toFloat() * 0.75f).toInt(),
                WindowManager.LayoutParams.WRAP_CONTENT
            )
        }
    }
}